import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:t_flutter_test/pages/file_09/home/component/search.dart';
import 'package:t_flutter_test/pages/file_09/home/component/swiper.dart';
import 'package:t_flutter_test/pages/file_09/home/component/nav.dart';
import 'package:t_flutter_test/pages/file_09/home/component/goods.dart';

class File09HomePage extends StatefulWidget {
  const File09HomePage({super.key});

  @override
  File09HomePageState createState() => File09HomePageState();
}

class File09HomePageState extends State<File09HomePage> {
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: 'http://smart-shop.itheima.net/index.php?s=/api/',
      connectTimeout: Duration(seconds: 10), // 连接超时
      receiveTimeout: Duration(seconds: 30), // 接收超时
    ),
  );

  List _swiperList = [];
  List _navList = [];
  String _adUrl = ''; // 广告图片地址
  List _goodsList = []; // 猜你喜欢商品列表

  // 获取数据
  _getData() {
    _dio
        .get('page/detail')
        .then((res) {
          List items = res.data['data']['pageData']['items'];
          setState(() {
            _swiperList = items[1]['data'];
            _navList = items[3]['data'];
            _adUrl = items[4]['data'][0]['imgUrl'] ?? '';
            _goodsList = items[6]['data'];
          });
        })
        .catchError((onError) {
          debugPrint('获取数据报错 error: $onError');
        });
  }

  @override
  void initState() {
    _getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('智慧商城', style: TextStyle(color: Colors.white)),
        centerTitle: true,
        backgroundColor: Colors.red,
        automaticallyImplyLeading: false,
      ),
      body: Column(
        children: [
          File09HomeSearch(),
          Expanded(
            child: ListView(
              children: [
                File09HomeSwiper(swiperList: _swiperList),
                File09HomeNav(navList: _navList),
                // 处理 _adUrl  一开始为空
                _adUrl == ''
                    ? Container()
                    : Image.network(_adUrl, fit: BoxFit.cover),
                Container(
                  margin: EdgeInsets.only(top: 10),
                  alignment: Alignment.center,
                  child: const Text('—— 猜你喜欢 ——'),
                ),
                File09HomeGoods(goodsList: _goodsList),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
